import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'

// 创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 添加token到请求头
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }

    return config
  },
  (error) => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const { data } = response

    // 统一处理响应格式
    if (data.success === false) {
      ElMessage.error(data.message || '请求失败')
      return Promise.reject(new Error(data.message || '请求失败'))
    }

    return data
  },
  (error) => {
    const DEBUG = import.meta.env.VITE_DEBUG === 'true'
    if (DEBUG) {
      console.error('响应错误:', error?.response || error)
    }

    // 处理不同的错误状态码
    if (error.response) {
      const { status, data } = error.response
      const url = error.config?.url || ''
      const isAuth = url.includes('/auth/login') || url.includes('/auth/register')

      switch (status) {
        case 401:
          if (isAuth) {
            break
          }
          const userStore = useUserStore()
          const hasToken = !!userStore.token
          userStore.showLoginModal = true
          if (hasToken) {
            userStore.token = ''
            userStore.userInfo = null
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
            ElMessage.error('登录已过期，请重新登录')
          } else {
            ElMessage.warning('请先登录后再操作')
          }
          break
        case 403:
          ElMessage.error('没有权限访问')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        case 413:
          ElMessage.error('请求体过大，请减小上传内容')
          break
        default:
          ElMessage.error(data?.message || '请求失败')
      }
    } else if (error.request) {
      ElMessage.error('网络连接失败，请检查网络')
    } else {
      ElMessage.error('请求配置错误')
    }
    const normalized = new Error(error?.response?.data?.message || error?.message || '请求失败')
    return Promise.reject(normalized)
  }
)

export default request
export const resolveImage = (url) => {
  if (!url) return ''
  return url
}